package com.wbcs.config.database.datasource;

import java.sql.Connection;

import javax.sql.DataSource;

import org.dom4j.Element;

import com.wbcs.config.ConfigLoadManager;
import com.wbcs.config.database.type.AbsDatabaseType;
import com.wbcs.exception.WbcsConfigLoadingException;

public abstract class AbsDataSource
{
    private String name;

    private AbsDatabaseType dbType;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name=name;
    }

    public AbsDatabaseType getDbType()
    {
        return dbType;
    }

    public void setDbType(AbsDatabaseType dbType)
    {
        this.dbType=dbType;
    }
    
    public void closePool()
    {
    }
    
    public  void loadConfig(Element eleDataSource)
    {
        
        String dbtype=eleDataSource.attributeValue("dbtype");
        if(dbtype==null||dbtype.trim().equals(""))
        {
            throw new WbcsConfigLoadingException("必须配置数据源的dbtype属性");
        }
        Class c;
        try
        {
            c=ConfigLoadManager.currentDynClassLoader.loadClassByCurrentLoader(dbtype.trim());
        }catch(Exception e)
        {
            throw new WbcsConfigLoadingException("配置的dbtype："+dbtype+"，无法加载此类",e);
        }
        Object o;
        try
        {
            o=c.newInstance();
        }catch(Exception e)
        {
            throw new WbcsConfigLoadingException("配置的dbtype："+dbtype+"，无法实例化此类的对象",e);
        }
        if(!(o instanceof AbsDatabaseType))
        {
            throw new WbcsConfigLoadingException("配置的dbtype："+dbtype+"对应的类没有继承"
                    +AbsDatabaseType.class.getName()+"超类");
        }
        this.dbType=(AbsDatabaseType)o;
    }
    
    public abstract Connection getConnection();
    
    public abstract DataSource getDataSource();
}
